package bodyAngle;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import comms.KinectClient;

public class AnglesApp {

	private AngleStorage angles;
	private Timer t;
	private KinectClient client = null;
	final TimerTask anglesUpdateTask = new TimerTask(){
		@Override
		public void run() {
			try {
				client.forwardMessageToServer(angles.toString());
			} catch (IOException e) {
			}	
		}
	};

	public AnglesApp(KinectClient c){
		client = c;
		angles = new AngleStorage();
        t = new Timer();
	}
	
	public synchronized void updateBodyAngle(String bodyPlace, double angle, String s){
		if(angles.getBodyAngle(bodyPlace) == null)
			angles.addBodyPlace(bodyPlace);
		Angle place = angles.getBodyAngle(bodyPlace);
		if(place.timeInSeconds()>0.015){ //15hz
			place.updateAngularVelocityAndAngle(System.currentTimeMillis(), angle);
			if(place.getAngularVelocity() > 1 || place.getAngularVelocity() < -1)
				System.out.println(place);
		}
	}
	
	public void scheduleAngleUpdate(){
		try{
			t.scheduleAtFixedRate(anglesUpdateTask, 0, 5000);
		}catch(IllegalStateException e ){
			System.err.println(e);
		}
	}
	
}
